#!/bin/bash

BLOCKSIZE=50000
VER=0.3.2

function split_to_dir
{
    INDEX="$1"
    OUT="$2"
    DIR=`dirname "$1"`
    NAME=`basename "$INDEX" .index`

    split -a 3 -b $BLOCKSIZE -d "$DIR/$NAME".index x-$NAME.index
    mv x-$NAME.index* "$OUT"

    if [ -f "$DIR/$NAME".dict ]; then
        split -a 3 -b $BLOCKSIZE -d "$DIR/$NAME".dict x-$NAME.dict
    elif [ -f "$DIR/$NAME".dict.dz ]; then
        gunzip -dc "$DIR/$NAME".dict.dz > Xtmp.dict
        split -a 3 -b $BLOCKSIZE -d Xtmp.dict x-$NAME.dict
        rm Xtmp.dict
    fi

    mv x-$NAME.dict* "$OUT"
}

if [ $# -ne 1 ]; then
    echo "usage: $0 dictionary.index"
    exit 1
fi

BASE=`basename $1 .index`

mkdir -p "$BASE"
mkdir -p "$BASE"/jdict
cp ../src/output/jdict/*.class "$BASE"/jdict
#mkdir -p "$BASE"/icones
#cp ../src/icones/* "$BASE"/icones
mkdir -p "$BASE"/dicts
split_to_dir $1 "$BASE"/dicts
echo $BLOCKSIZE > "$BASE"/dicts/BLOCKSIZE
wc -c < "$1" > "$BASE"/dicts/TOPINDEX
echo $BASE > "$BASE"/dicts/VORTARO
mkdir -p "$BASE"/META-INF

cat > "$BASE".MANIFEST.MF <<END
MIDlet-1: jdict, , jdict.Main
MIDlet-Name: $BASE
MIDlet-Vendor: viric
MIDlet-Version: $VER
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
END

cd "$BASE"
jar cmf ../"$BASE".MANIFEST.MF ../"$BASE".jar *
cd ..
rm "$BASE".MANIFEST.MF
